﻿using System;
using System.Text;

namespace Bookvar.Console
{
    internal sealed class CommandBuffer
    {
        private readonly ILanguageEngine engine;
        private readonly StringBuilder commandText;

        public CommandBuffer( ILanguageEngine engine )
        {
            if ( engine == null )
            {
                throw new ArgumentNullException( "engine" );
            }
            this.engine = engine;
            commandText = new StringBuilder();
        }

        public string Text
        {
            get { return commandText.ToString(); }
        }

        public object Add( string text )
        {
            if (engine.IsExpressionValid(text) && commandText.Length == 0)
            {
                return engine.ScriptEngine.Evaluate(text, engine.CurrentModule);
            }

            if ( commandText.Length > 0 )
            {
                commandText.AppendLine();
            }
            commandText.Append( text );
            string code = commandText.ToString();
            if ( engine.IsStatementComplete( code ) )
            {
                try
                {
                    engine.ScriptEngine.Execute( code, engine.CurrentModule );
                }
                finally
                {
                    commandText.Length = 0;
                }
            }

            return null;
        }
    }
}